<template>
  <div class="panel-work" v-loading="drawing">
    <main>
      <div class="msg-card" v-if="!assistantResumeVo">
        <img :src="setSuccessImg" alt="" class="img" />
        <div class="text">
          <h3>设置成功</h3>
          <p v-if="userInfo" style="color: #707070; margin-top: 12px">
            {{ userInfo.realname }}
          </p>
          <p style="color: #707070; margin-top: 6px">
            前往简历页面即可自动获取简历信息
          </p>
        </div>
      </div>

      <resume-preview
        v-if="assistantResumeVo"
        :data="assistantResumeVo"
        :repeatResume="repeatResume"
        @onExternalFormChange="onExternalFormChange"
      />
      <resume-options
        v-if="assistantResumeVo"
        :externalForm="externalForm"
        :data="assistantResumeVo"
        :repeatResume="repeatResume"
        :domToBeSaveImg="domToBeSaveImg"
      />
    </main>
  </div>
</template>

<script>
import $ from "jquery"
import { getFromStorage, sleep } from "../lib"
import ResumePreview from "./components/resume-preview"
import ResumeOptions from "./components/resume-options"
const setSuccessImg = chrome.runtime.getURL("assets/set_success@2x.png")

let findingTask
export default {
  name: "PanelWork",
  props: {
    panelVisible: Boolean,
    onPanelVisible: Function,
    userInfo: Object,
    sites: Array,
  },
  components: {
    ResumePreview,
    ResumeOptions,
  },
  data() {
    return {
      domainList: [
        {
          domain: "www.zhipin.com",
          name: "boss直聘",
        },
        {
          domain: "ehire.51job.com",
          name: "51job",
        },
        {
          domain: "rd6.zhaopin.com",
          name: "智联",
        },
        {
          domain: "lpt.liepin.com",
          name: "猎聘",
        },
      ],
      setSuccessImg,
      drawing: false,
      assistantResumeVo: undefined,
      repeatResume: undefined,

      domToBeSaveImg: undefined,

      targetSite: undefined,
      targetSites: [],
      targetDomContainer: undefined,
      targetDomIsIframe: false,
      lastDomUser: undefined,
      observer: undefined,

      externalForm: {},
    }
  },
  watch: {
    targetDomContainer(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        // 监听targetDomContainer内容是否发生变化
        if (this.targetDomContainer) {
          // 避免重复监听
          if (this.observer) this.observer.disconnect()

          const observer = new MutationObserver((mutations) => {
            if (this.drawing) return
            mutations.forEach((mutation) => {
              if (mutation.type === "childList") {
                const { resumeDom, isIframeVisible, iframeElement } =
                  this.getResumeDom("MutationObserver")

                if (resumeDom) {
                  let needDelayFecthDom
                  console.log("3. 获取到resumeDom: ", resumeDom)
                  let currentUser
                  if (isIframeVisible) {
                    if (this.targetSite.iframeUserSelector) {
                      currentUser = resumeDom.querySelector(
                        this.targetSite.iframeUserSelector
                      )?.innerHTML
                    } else {
                      currentUser = iframeElement.src
                      needDelayFecthDom = true
                    }
                  } else {
                    currentUser = resumeDom.querySelector(
                      this.targetSite.userSelector
                    )?.innerHTML
                  }
                  console.log("3.1 当前用户: ", currentUser)
                  console.log("3.2 上一个用户: ", this.lastDomUser)
                  if (currentUser && currentUser !== this.lastDomUser) {
                    console.log(
                      "4. 确认是新的用户，开始解析: ",
                      currentUser,
                      this.resumeDom
                    )
                    this.getResume("MutationObserver", needDelayFecthDom)
                    this.lastDomUser = currentUser
                  }
                } else {
                  console.log("3. 未获取到resumeDom...")
                }
              }
            })
          })

          console.log("2.开始监听目标容器:>>", this.targetDomContainer)
          observer.observe(this.targetDomContainer, {
            childList: true,
            subtree: true,
          })
          this.observer = observer
        }
      }
    },
    panelVisible(newVal) {
      if (newVal) {
        // 助手出现时，立即尝试开始解析
        this.beginTask("panelVisible=true")
      } else {
        // 助手隐藏时，停止解析
        this.endTask()
      }
    },
  },
  methods: {
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },

    getResumeContainer() {
      return this.targetDomContainer
    },

    getResumeDom(from) {
      console.log("getResumeDom triggered from: >>", from)
      let isIframeVisible = false
      let iframeElement
      // 优先查找resumeSelector，如果有iframe存在，则去iframe内部查找iframeContainerSelector
      let resumeDom = this.targetDomContainer.querySelector(
        this.targetSite.resumeSelector
      )
      if (this.targetSite.iframe) {
        iframeElement = document.querySelector(this.targetSite.iframe)
        if (iframeElement) {
          isIframeVisible = true
          const doc =
            iframeElement.contentDocument ||
            iframeElement.contentWindow.document
          if (doc) {
            const isIframeContentLoaded = doc.querySelector(
              this.targetSite.iframeResumeVisibleSelector
            )
            if (isIframeContentLoaded) {
              resumeDom = doc.querySelector(
                this.targetSite.iframeResumeSelector
              )
            }
          }
        }
      }

      return {
        resumeDom,
        isIframeVisible,
        iframeElement,
      }
    },

    async getResume(from, needDelayFecthDom) {
      if (!this.panelVisible || this.drawing) return

      let originalDom
      if (needDelayFecthDom) {
        let _resumeDom
        let retryCount = 0
        while (!_resumeDom) {
          if (retryCount > 20) break
          retryCount++
          const { resumeDom } = this.getResumeDom("needDelayFecthDom")
          _resumeDom = resumeDom
          await sleep(300)
        }
        originalDom = _resumeDom
      } else {
        const { resumeDom } = this.getResumeDom("normal")
        originalDom = resumeDom
      }

      console.log("getResume from: >>", from)
      const resumeDom = originalDom ? $(originalDom).clone() : undefined
      this.domToBeSaveImg = originalDom
      if (resumeDom) {
        console.log("5. 获取到resumeDom: ", resumeDom)
        if (this.targetSite.ignoreSelectors) {
          this.targetSite.ignoreSelectors.forEach((selector) => {
            const ignoreElement = resumeDom.find(selector)
            if (ignoreElement) {
              ignoreElement.remove()
            }
          })
        }

        this.drawing = true

        const fileHtml = needDelayFecthDom
          ? originalDom.innerHTML
          : resumeDom.html()
        const fileContent = `<!DOCTYPE html>
          <html>
          <body>
            ${fileHtml}
          </body>
          </html>`

        const htmlfile = new File([fileContent], `${Date.now()}.html`, {
          type: "text/plain;charset=utf-8",
          lastModified: Date.now(),
        })

        const forms = new FormData()
        forms.append("file", htmlfile)
        // forms.append('pic', picFile)
        console.log("6. 开始提交resumeDom")
        const HRMS_LOGIN_HOST = await getFromStorage("HRMS_LOGIN_HOST")
        try {
          const res = await this.axios.post(
            HRMS_LOGIN_HOST + "/hrms/recruit/assistant/importResume",
            forms,
            { headers: { "Content-Type": "multipart/form-data" } }
          )
          console.log("7. 提交resumeDom解析成功，解析后的数据：", res)
          const { assistantResumeVo = {}, repeatResume } = res
          console.log("7.1 assistantResumeVo: ", assistantResumeVo)
          console.log("7.2 repeatResume: ", repeatResume)

          this.repeatResume = repeatResume
          this.assistantResumeVo = assistantResumeVo

          // 直接获取域名
          const domain = window.location.hostname
          const foundItem = this.domainList.find((item) =>
            domain.includes(item.domain)
          )
          if (foundItem) {
            this.repeatResume.resumeSource = foundItem //  // 赋值简历来源
          } else {
            console.log("未找到对应的名称")
          }
          this.drawing = false

          if (from === "MANUAL") {
            this.$this.$message.success("手动解析成功")
          }
        } catch (error) {
          this.drawing = false
        }
      } else {
        console.log("5. 未取到resumeDom...")
        console.log("没有找到目标元素...")
      }
    },

    findTargetSite() {
      const host = window.location.host
      const href = window.location.href
      const selectors = this.sites.filter((d) => host.includes(d.name))
      const site = selectors.find((d) => href.includes(d.path))
      this.targetSite = site
      console.log("命中目标 site: >>", site)
    },

    findTargetContainer() {
      // if(this.observer) return

      if (this.targetSite) {
        let container = document.querySelector(
          this.targetSite.containerSelector
        )
        if (this.targetSite.iframe) {
          const iframeElement = document.querySelector(this.targetSite.iframe)
          if (iframeElement) {
            const doc =
              iframeElement.contentDocument ||
              iframeElement.contentWindow.document
            if (doc) {
              container = doc.querySelector(
                this.targetSite.iframeContainerSelector
              )
            }
          }
        }

        if (container) {
          console.log("1.找到目标容器:>>", container)
          this.targetDomContainer = container

          console.log("1.1 开始自动解析 ")
          this.getResume("findTargetContainer")
          this.endTask()
        }
      }
    },
    beginTask(from) {
      console.log("beginTask triggered from: >>", from)
      this.findTargetSite()

      this.endTask()

      findingTask = setInterval(() => {
        this.findTargetContainer()
      }, 500)
    },
    endTask() {
      if (findingTask) {
        clearInterval(findingTask)
      }
    },

    onExternalFormChange(val) {
      this.externalForm = val
    },
  },
  mounted() {
    if (this.panelVisible) {
      this.beginTask("mounted")
    }

    let self = this
    chrome.runtime.onMessage.addListener(
      // eslint-disable-next-line no-unused-vars
      function (request, sender, sendResponse) {
        // listen for messages sent from background.js
        if (request.message === "PAGE_URL_CHANGED") {
          console.log("listener updated on: ", request.url)
          self.beginTask("PAGE_URL_CHANGED")
        }
      }
    )
  },
  unmounted() {
    this.endTask()
  },
}
</script>

<style lang="less" scoped>
@import "./styles/panel-work.less";
</style>
